/*
* Create by yz_wy_power on 2018/5/25
*/

/**
 * 为axios添加一些默认属性
 * 存储authToken
 * 登陆auth判断
 */
import axios from 'axios'
import $cache from './cache'
import iview from 'iview'

axios.defaults.timeout = 60000;
axios.defaults.withCredentials = false;
axios.defaults.headers.common['auth'] = $cache.get('auth');
//在请求或响应被 then/catch之前做点操作

axios.interceptors.request.use((config) => {
  let authVal = config.headers.common && config.headers.common.auth;
  if (!authVal) {
    console.log('-------')
  } else {
    console.log('~~~~~~~')
  }
  return config
}, (error) => {

  return Promise.reject(error)
});

/**
 * 1.对响应数据/错误响应做点什么
 * 2.如果在有效期内部，请求成功(code===0)，缓存token有效期以当前时间点继续延续
 * 3.如果(code===401),则表示未登录或者异处登录，重新刷新，并清除token缓存
 * */
axios.interceptors.response.use(function (response) {
  let code = response.data.error_code,
    cacheGetAuthToken = $cache.get('auth');
  if (code === 0) {
    $cache.set('auth', cacheGetAuthToken, window.limitTime_yzdev);
  } else if (code === 20544) {
    $cache.del('auth');
    $cache.del('dev_info');
    iview.Message.error({
      content: '登录过期，请重新登录',
    });
    setTimeout(() => {
      window.location.reload();
    }, 1500);
  }
  return response;
}, function (error) {
  return Promise.reject(error);
});

//window.limitTime 存储信息的时效
getLimitTime();

function getLimitTime() {
  let limitTime = 120 * 60 * 60;
  if (window.limitTime_yzdev) {
    window.limitTime_yzdev = limitTime
  } else {
    window.limitTime_yzdev = limitTime
  }
}

function Auth({auth = '', error = ''}) {
  let cacheGetAuthToken = $cache.get('auth');
  if (auth) {
    $cache.set('auth', auth, window.limitTime_yzdev);
    return auth
  }
  if (error) {
    return false
  }
  return !!cacheGetAuthToken
}

/*
* 1.获取用户信息，key值为'userInfo'
* 2.兼容删除auth信息
* */
function handleUserInfo({userInfo = 'admin', type}) {
  switch (type) {
    case 'set':
      $cache.set('userInfo', userInfo, window.limitTime_yzdev);
      break;
    case 'get':
      return $cache.get('userInfo');
    case 'del':
      $cache.del(userInfo)
  }
}

export {
  Auth,
  handleUserInfo
}
